package com.lee.lease.common.interceptor;

import com.lee.lease.common.custom.exception.LeaseException;
import com.lee.lease.common.result.ResultCodeEnum;
import com.lee.lease.common.threadlocal.LoginUser;
import com.lee.lease.common.threadlocal.LoginUserContext;
import com.lee.lease.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName: LoginInterceptor
 * Package: com.lee.lease.web.admin.custom.interceptor
 * Description:
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginUserContext loginUserContext;
    private long start;
    private long end;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        start = System.currentTimeMillis();
        String token = request.getHeader("access_token");
        if (token == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        //解析token
        Claims claims = JwtUtil.parseToken(token);

        //利用本地线程存储用户信息,实现当前线程中用户信息共享
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        LoginUser loginUser = new LoginUser(userId, username);
        loginUserContext.setLoginUser(loginUser);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        end = System.currentTimeMillis();

        //最后一定要讲当先线程中的数据移除,否则会造成内存泄漏
        loginUserContext.clear();

        //性能分析
        System.out.println(end-start);
    }
}
